{% extends "base.html" %}
{% block content %}
<div class="new">
  <h2> Create a new note. </h2>
  <form method="post" action="/note_create/">
  <label for="title">Title</label>
  <input type="text" name="title" id="title">
  <label for="slug">Slug</label>
  <input type="text" name="slug" id="slug">
  <input type="submit" value="create note">
  </form>
</div>
<div class="list">
  <h2> Notes </h2>
  <ol id="notes">
    {% for object in object_list %}
    <li><a href="{{ object.get_absolute_url }}">{{ object.title }}</a></li>
    {% endfor %}
  </ol>
</div>
<script>
var create_note = function() {
  var title = $("#title").val()
  var slug = $("#slug").val()
  if (title != "" && slug != "") {
    var data = { title:title, slug:slug };
    var args = { type:"POST", url:"/create/", data:data, complete:done };
    $.ajax(args);
  }
  else {
    // display an explanation of failure
  }
  return false;
};
var done = function(res, status) {
  if (status == "success") {
    var txt = res.responseText;
    var titleStr = txt.match(/id="title" value="\w+"/ig)[0];
    var slugStr = txt.match(/id="slug" value="\w+"/ig)[0];
    var title = titleStr.match(/"\w+"/ig)[1].replace(/"/g,'');
    var slug = slugStr.match(/"\w+"/ig)[1].replace(/"/g,'');
    var newLi = $('<li><a href="/note/'+slug+'">'+title+'</a></li>');
    $("#notes").prepend(newLi);
    $("#title").val("");
    $("#slug").val("");
  }
  else {
    // display an explanation of failure
  }
}
</script>
{% endblock %}
